import { useState, Suspense, useEffect, useRef } from 'react';
import {
    TeamOutlined,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    UserOutlined,
    DownOutlined,
    BellOutlined,
    ExpandOutlined
} from '@ant-design/icons';
import "../assets/css/index.scss"
import FullScreen from '../components/FullScreen';
import { Select, Layout, Menu, theme, Button, Col, Row, Breadcrumb, Tabs, Dropdown, Space, Flex } from 'antd';
import { useNavigate, Outlet, useLocation, Link } from "react-router-dom"
const { Header, Content, Footer, Sider } = Layout;

const items = [

    {
        key: "key1",
        icon: <UserOutlined />,
        label: "运营",
        children: [
            {
                key: "/",//路径
                label: "控制台",
            },
            {
                key: "/goodscount",
                label: "商品统计",

            }
        ]
    },
    {
        key: "key2",
        icon: <UserOutlined />,
        label: "商品",
        children: [
            {
                key: "/goodsmanger",
                label: "商品管理",
            },
            {
                key: "/goodstype",
                label: "商品分类",
            },
            {
                key: "/goodsspecs",
                label: "商品规格",
            }
          
        ]
    },
    {
        key: "key3",
        icon: <UserOutlined />,
        label: "商品订单",
        children: [
            {
                key: "/goodesorder",
                label: "订单",
            },
            {
                key: "/userrank",
                label: "用户排序",
            },
            {
                key: "/usermanger",
                label: "用户管理",
            },
           
          
        ]
    },
    {
        key: "key4",
        icon: <UserOutlined />,
        label: "内容",
        children: [
            {
                key: "/articletype",
                label: "文章分类",
            },
            {
                key: "/articlemanger",
                label: "文章管理",
            },
           
           
          
        ]
    }
];

const downlist = [//下拉
    {
        key: '/',
        label: <Link to="/">首页</Link>,
    },
    {
        key: '/my',
        label: <Link to="/my">个人中心</Link>,// 未设置页面
    },
    {
        key: '/buju',
        label: <Link to="/buju">布局设置</Link>,// 未设置页面
    },
    {
        key: '/login',
        label: <Link to="/login">退出</Link>,
    },
];
const App = () => {
    const route = useLocation()//获取本地页面的所有的信息
    const navigate = useNavigate()
    const [collapsed, setCollapsed] = useState(false);
    const { token: { colorBgContainer, borderRadiusLG } } = theme.useToken();

    const [openKey, setOpenKey] = useState([""])//展示那个模块
    const [path, setPath] = useState([""])
    const [navitem, setNavitem] = useState([
        {
            title: <a href='/'>首页</a>,
        },
        {
            title: <a href='/'>运营</a>,
        },
        {
            title: "控制台",
        }

    ])
    const openFun = (res) => {
        setOpenKey([res[res.length - 1]])
    }
    const clickItem = (res) => {//单机左侧菜单跳转*******************************
        // console.log(res.key);//路径
        if (res.key == route.pathname) {
            return false
        }
        setPath([res.key])
        navigate(res.key)
        items.map(item => {

            item.children.map(sonitem => {
                if (res.key == sonitem.key) {
                    // *********************************下拉联动
                    setValue(sonitem.label)
                    setNavitem(pre => {// 面包屑
                        pre[pre.length - 2].title = <Link to={item.children[0].key}>{item.label}</Link>
                        pre[pre.length - 1].title = sonitem.label
                        return [...pre]
                    })
                    setActiveKey(res.key)

                    let index = itemss.findIndex(item => res.key == item.key)//es6找下标
                    if (index == -1) {
                        setItemss(arry => {
                            arry.push({
                                label: sonitem.label,
                                key: res.key
                            })
                            return [...arry]
                        })
                    }
                }
            })
        })






    }

    const routeFun = () => {// 刚进入页面 记录状态

        items.map(item => {
            item.children.map(sonitem => {
                if (route.pathname == sonitem.key) {
                    // console.log(sonitem.label);

                    setOpenKey([item.key])// 打开选中的父类
                    setPath([sonitem.key])

                    setNavitem(pre => {
                        // console.log(pre);

                        pre[pre.length - 2].title = <Link to={item.children[0].key}>{item.label}</Link>
                        pre[pre.length - 1].title = sonitem.label
                        return [...pre]
                    })

                    setItemss([
                        {
                            label: sonitem.label,
                            key: sonitem.key,
                        }
                    ])
                }
            })
        })
    }


    useEffect(() => {
        // console.log("生命周期");
        // console.log(route.pathname);
        setActiveKey(route.pathname)
        routeFun()

        filterItems()//过滤
    }, [])
    const clickNav = (e) => {//面包屑导航单机
        let attr = e.target.getAttribute("href")
        // console.log(attr);
        // setPath(attr)
        // setActiveKey(attr)
        clickItem({ key: attr })
    }
    // 下面是tabs切换效果
    const [activeKey, setActiveKey] = useState("");
    const [itemss, setItemss] = useState([// tab选项卡切换
        {
            label: '控制台',
            key: '/',
        }
    ]);
    const newTabIndex = useRef(0);
    const onChange = (newActiveKey) => {
        setActiveKey(newActiveKey);
    };

    const remove = (targetKey) => {
        let newActiveKey = activeKey;
        let lastIndex = -1;
        itemss.forEach((item, i) => {
            if (item.key === targetKey) {
                lastIndex = i - 1;
            }
        });
        const newPanes = itemss.filter((item) => item.key !== targetKey);
        if (newPanes.length && newActiveKey === targetKey) {
            if (lastIndex >= 0) {
                newActiveKey = newPanes[lastIndex].key;
            } else {
                newActiveKey = newPanes[0].key;
            }
        }
        setItemss(newPanes);
        setActiveKey(newActiveKey);
    };
    const onEdit = (targetKey, action) => {
        console.log(targetKey, action);
        if (action === 'add') {//增加
            //   add();
        } else {//删除
            console.log(action);
            remove(targetKey);
        }
    };



    const onTabClick = (targetKey) => {// 单机tab选项卡
        items.map(item => {
            item.children.map(sonitem => {
                if (targetKey == sonitem.key) {
                    setValue(sonitem.label)
                    setOpenKey([item.key])// 打开选中的父类

                    setNavitem(pre => {
                        pre[pre.length - 2].title = <Link to={item.children[0].key}>{item.label}</Link>
                        pre[pre.length - 1].title = sonitem.label
                        return [...pre]
                    })
                }
            })
        })
        setPath(targetKey)
        navigate(targetKey)
    }

    const onclickItem = ({ key }) => {// 单机下拉首页 跳转到首页页面
        if (key == "/") {
            setOpenKey(["key1"])// 跳转首页
            setPath("/")// 跳转首页
            clickItem({ key: "/" })//复用了单机左侧菜单的函数 注意参数是一个对象
        }
    }



    // 下面是下拉搜索 事件
    const [options, setOptions] = useState([])

    const filterItems = () => {
        let arry = []
        items.map(item => {
            item.children.map(sonitem => {
                arry.push({
                    value: sonitem.key,
                    label: sonitem.label,
                })
            })
        })
        setOptions(arry);
    }
    const onSearchChange = (value) => {//选中目标 展开菜单 添加样式 
        clickItem({ key: value })//复用了单机左侧菜单的函数 注意参数是一个对象
        onTabClick(value)
    }
    const [value, setValue] = useState("")

    // 下面是全屏


    return (
        <Layout hasSider>

            <Sider style={{
                overflow: 'auto',
                height: '100vh',
                position: 'fixed',
                left: 0,
                top: 0,
                bottom: 0,
            }} trigger={null} collapsible collapsed={collapsed}>
                <div className="demo-logo-vertical" />
                <Menu
                    theme="dark"
                    mode="inline"
                    selectedKeys={path}
                    openKeys={openKey}
                    items={items}
                    onOpenChange={(e) => openFun(e)}
                    onClick={(e) => clickItem(e)}
                />
            </Sider>
            <Layout style={{
                marginLeft: 200,
            }}>
                <Header
                    style={{
                        position: 'sticky',
                        top: 0,
                        zIndex: 99,
                        width: '100%',
                        padding: "0 16px 0 16px",
                        background: colorBgContainer, 
                    }}
                >
                    <Flex justify='space-between'>
                        <Flex align='center'>


                            <Button
                                type="text"
                                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                                onClick={() => setCollapsed(!collapsed)}
                            />

                            <Breadcrumb
                                className='breadcrumb'
                                items={navitem}
                                onClick={(e) => { clickNav(e) }}
                            >


                            </Breadcrumb>

                        </Flex>

                        <Flex align='center'>

                            <Select
                                showSearch
                                style={{
                                    width: 200,
                                }}
                                placeholder="搜索菜单"
                                value={value}
                                optionFilterProp="label"
                                filterSort={(optionA, optionB) =>
                                    (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                                }
                                options={options}
                                onChange={onSearchChange}
                            />
                            <FullScreen ></FullScreen>
                            {/* <ExpandOutlined onClick={toggleFullScreen} /> */}
                            <BellOutlined className='icon' />
                            <Dropdown
                                menu={{
                                    items: downlist,
                                    onClick: onclickItem
                                }}
                            >
                                <a onClick={(e) => e.preventDefault()}>
                                    <Space>
                                        demo
                                        <DownOutlined />
                                    </Space>
                                </a>
                            </Dropdown>
                        </Flex>
                    </Flex>
                    <Tabs
                        style={{
                            background:"#f5f5f5",
                            paddingTop:"5px"
                        }}
                        type="editable-card"
                        onChange={onChange}
                        activeKey={activeKey}
                        onEdit={onEdit}
                        items={itemss}
                        onTabClick={onTabClick}
                        hideAdd={true}
                        size="small"
                    />
                </Header>
                <Content style={{ margin: '16px',paddingTop:"45px" }}>
                    <Suspense fallback={<div>加载中...</div>}>
                        <Outlet></Outlet>
                    </Suspense>
                </Content>

                <Footer style={{ textAlign: 'center' }}>官网社区文档</Footer>
            </Layout>
        </Layout>
    );
};
export default App;